package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a07_组合总和
 * </p>
 *
 * @author flyduck
 * @since 2025-01-01
 */
public class a07_组合总和 {

    public static void main(String[] args) {
        int[] nums = new int[]{2,3,6,7};
        a07_组合总和 test = new a07_组合总和();
        List<List<Integer>> lists = test.combinationSum(nums, 7);
        System.out.println(lists);
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> resultList = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(resultList, path, candidates, target, 0, 0);
        return resultList;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int[] candidates,
                           int targetSum,
                           int sum,
                           int startIdx){
        if(sum > targetSum){
            return;
        }
        if(sum == targetSum){
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = startIdx; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum = sum + candidates[i];
            traversal(result, path, candidates, targetSum, sum, i);
            path.removeLast();
            sum = sum - candidates[i];
        }

    }
}
